package com.qiwenshare.file.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiwenshare.common.exception.QiwenException;
import com.qiwenshare.common.util.DateUtil;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.api.ArchiveApproveStepService;
import com.qiwenshare.file.api.ArchiveService;
import com.qiwenshare.file.constant.ApproveStatusEnum;
import com.qiwenshare.file.domain.ArchiveApproveFlowItem;
import com.qiwenshare.file.domain.ArchiveApproveStep;
import com.qiwenshare.file.dto.archive.ApproveDTO;
import com.qiwenshare.file.mapper.ArchiveApproveFlowItemMapper;
import com.qiwenshare.file.mapper.ArchiveApproveMapper;
import com.qiwenshare.file.domain.ArchiveApprove;
import com.qiwenshare.file.api.ArchiveApproveService;
import com.qiwenshare.file.mapper.ArchiveApproveStepMapper;
import com.qiwenshare.file.vo.ArchiveApproveStepVo;
import com.qiwenshare.file.vo.ArchiveApproveVo;
import com.qiwenshare.file.vo.archive.ArchiveVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * 用户档案审批表(ArchiveApprove)表服务实现类
 *
 * @author MJ
 * @since 2023-10-12 16:51:48
 */
@Service("archiveApproveService")
public class ArchiveApproveServiceImpl extends ServiceImpl<ArchiveApproveMapper, ArchiveApprove> implements ArchiveApproveService {

    @Autowired
    private ArchiveApproveMapper archiveApproveMapper;

    @Autowired
    private ArchiveApproveStepMapper archiveApproveStepMapper;

    @Autowired
    private ArchiveService archiveService;

    @Autowired
    private ArchiveApproveFlowItemMapper archiveApproveFlowItemMapper;

    @Override
    public IPage<ArchiveApproveVo> getVoList(String archiveName, String userName, Integer approveStatus, Long currentPage, Long pageCount) {
        Page<ArchiveApproveVo> page = new Page<>(currentPage, pageCount);
        if (approveStatus == 1) {
            return archiveApproveMapper.selectPageVo(page, archiveName, userName, approveStatus, SessionUtil.getUserId());
        } else {
            return archiveApproveMapper.selectApproveedPageVo(page, archiveName, userName, SessionUtil.getUserId());
        }
    }

    @Override
    public ArchiveApproveVo getApproveOne(String archiveId, String applyUserId) {
        return archiveApproveMapper.getApproveOne(archiveId, applyUserId);
    }

    @Transactional(rollbackOn = Exception.class)
    @Override
    public Boolean approve(ApproveDTO approveDTO) {
        ArchiveApproveVo archiveApproveVo = archiveApproveMapper.selectApprove(approveDTO.getApproveId());
        ArchiveApproveStep approveStepVo = archiveApproveStepMapper.selectOne(new QueryWrapper<>(ArchiveApproveStep.builder()
                .stepId(archiveApproveVo.getCurrentStepId())
                .build()));
        String approveBy = SessionUtil.getUserId();
        if (!archiveApproveVo.getCurrentApproveByIds().contains(approveBy)) {
            throw new QiwenException("用户无权限审批");
        }
        if (ApproveStatusEnum.getEnum(approveDTO.getApproveStatus()).equals(ApproveStatusEnum.REJECT)) {
            //更新archiveApprove状态
            archiveApproveMapper.update(ArchiveApprove.builder()
                    .approveStatus(ApproveStatusEnum.REJECT.getStatus())
                    .historyApproveByIds(generateHistoryApproveByIds(archiveApproveVo.getHistoryApproveByIds(), SessionUtil.getUserId()))
                    .approveId(approveDTO.getApproveId())
                    .build(), new QueryWrapper<>(ArchiveApprove.builder()
                    .approveId(approveDTO.getApproveId())
                    .build()));
            //更新approveStep状态
            archiveApproveStepMapper.update(ArchiveApproveStep.builder()
                    .stepId(approveStepVo.getStepId())
                    .approveResult(ApproveStatusEnum.REJECT.getStatus())
                    .reason(approveDTO.getReason())
                    .createTime(DateUtil.getCurrentTime())
                    .createUserId(SessionUtil.getUserId())
                    .build(), new QueryWrapper<>(ArchiveApproveStep.builder()
                    .stepId(approveStepVo.getStepId())
                    .build()));
        } else {
            //更新archiveApprove状态
            ArchiveApproveStep nextStep = archiveApproveStepMapper.getNextStep(approveDTO.getApproveId(), approveStepVo.getStepId());
            //如果没有下一步，则结束流程
            if (nextStep == null) {
                //更新archiveApprove状态
                archiveApproveMapper.update(ArchiveApprove.builder()
                        .approveStatus(ApproveStatusEnum.SUCCESS.getStatus())
                        .currentApproveByIds(null)
                        .historyApproveByIds(generateHistoryApproveByIds(archiveApproveVo.getHistoryApproveByIds(), SessionUtil.getUserId()))
                        .approveId(approveDTO.getApproveId())
                        .build(), new QueryWrapper<>(ArchiveApprove.builder()
                        .approveId(approveDTO.getApproveId())
                        .build()));
            } else {
                //如果有下一步，则继续流程
                ArchiveApproveFlowItem nextItem = archiveApproveFlowItemMapper.selectOne(new QueryWrapper<>(ArchiveApproveFlowItem.builder()
                        .itemId(nextStep.getItemId())
                        .build()));
                archiveApproveMapper.update(ArchiveApprove.builder()
                        .currentStepId(nextStep.getStepId())
                        .historyApproveByIds(generateHistoryApproveByIds(archiveApproveVo.getHistoryApproveByIds(), SessionUtil.getUserId()))
                        .lastStepId(approveStepVo.getStepId())
                        .approveId(approveDTO.getApproveId())
                        .currentApproveByIds(archiveService.getCurrentApproveByIds(archiveApproveVo.getUserId(), archiveApproveVo.getArchiveId(), nextItem))
                        .build(), new QueryWrapper<>(ArchiveApprove.builder()
                        .approveId(approveDTO.getApproveId())
                        .build()));
            }
            //更新approveStep状态
            archiveApproveStepMapper.update(ArchiveApproveStep.builder()
                    .stepId(approveStepVo.getStepId())
                    .approveResult(ApproveStatusEnum.SUCCESS.getStatus())
                    .createTime(DateUtil.getCurrentTime())
                    .createUserId(SessionUtil.getUserId())
                    .build(), new QueryWrapper<>(ArchiveApproveStep.builder()
                    .stepId(approveStepVo.getStepId())
                    .build()));

        }
        return null;
    }

    private String generateHistoryApproveByIds(String oldHistoryApproveByIds, String newApproveBy) {
        if (StringUtils.isBlank(oldHistoryApproveByIds)) {
            return newApproveBy;
        } else {
            return oldHistoryApproveByIds + "," + newApproveBy;
        }
    }
}

